package com.bidevalution.business.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.bidevalution.business.service.BeParameterReferenceService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.business.service.BeSectionParameterService;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeMethodDefine;
import com.bidevalution.dao.entity.BeParameterReference;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.dao.entity.BeSectionParameterKey;
import com.bidevalution.dao.mapper.BeMethodDefineMapper;
import com.bidevalution.dao.mapper.BeSectionParameterMapper;
import com.bidevalution.support.util.LogUtil;
import com.bidevalution.support.util.MapUtil;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.redis.RedisUtil;

/**
 * 标段参数
 *
 * @author daizhifeng
 * @date 2019-08-06
 */
@Service
public class BeSectionParameterImpl implements BeSectionParameterService {
	@Autowired
	private BeSectionParameterMapper beSectionParameterMapper;
	@Autowired
	private JdbcTemplateService jdbcTemplateService;
	@Autowired
	private BeParameterReferenceService beParameterReferenceService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	private LogUtil logger = LogUtil.getLogManager(getClass());

	/**
	 * 计算标段参数公式值
	 *
	 * @param sectionMethodId
	 * @param dataMap
	 * @return
	 */
	public Map<String, Object> compute(String sectionId, Map<String, Object> dataMap) {
		Map<String, Object> dataResultMap = new HashMap<String, Object>();
//		for(BeSectionParameter beSectionParameter:beSectionParameterMapper.selectForList(sectionId)){
//			if("1".equals(beSectionParameter.getIsFormula()) && !StringUtils.isEmpty(beSectionParameter.getParamValue())){
//				dataResultMap.put(beSectionParameter.getParamCode(), AviatorEvaluator.execute(beSectionParameter.getParamValue(), dataMap));
//			}
//		}
		return dataResultMap;
	}

	@Override
	public List<BeSectionParameter> selectList(String sectionId) {
		// TODO Auto-generated method stub
		return beSectionParameterMapper.selectList(sectionId);
	}

	@Override
	public void save(String sectionId, Map<String, String> paramIdMap, BeParameterReference beParameterReference) {

		// 判断是否存在
		BeSectionParameterKey beSectionParameterKey = new BeSectionParameterKey();
		beSectionParameterKey.setParamId(beParameterReference.getParamId());
		beSectionParameterKey.setSectionId(sectionId);
		BeSectionParameter beSectionParameter = beSectionParameterMapper.selectByPrimaryKey(beSectionParameterKey);
		if (beSectionParameter == null && beParameterReference.getOriginParamId() != null) {
			// 新增
			beSectionParameter = new BeSectionParameter();
			beSectionParameter.setCreateTime(new Date());
			beSectionParameter.setParamId(beParameterReference.getParamId());
			beSectionParameter.setParamType("0");
			beSectionParameter.setParamValue(paramIdMap.get(beParameterReference.getOriginParamId().toLowerCase()));
			beSectionParameter.setDisplayType(beParameterReference.getDisplayType());
			beSectionParameter.setSectionId(sectionId);
			beSectionParameter.setUpdateTime(new Date());
			beSectionParameterMapper.insert(beSectionParameter);
		}

	}

	@Override
	public List<Map<String, Object>> selectGFSJTree(String sectionId, String parentId) {
		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
		List<Map<String, Object>> returnList = Lists.newArrayList();
		List<Map<String, Object>> childList = Lists.newArrayList();
		Map<String, Object> data = jdbcTemplateService.selectForMap(
				"select mano_ManageNodeID ,mano_Code,mano_Name, GF1,SJ from td_ManageNode a left join (select otco_ProjectID,otco_ManageNodeID,max(case otco_CostType when '4' then otco_Formula end) as GF1,null as GF2, null as GF3,max(case otco_CostType when '5' then otco_Formula end) as SJ from td_OtherCost group by otco_ProjectID,otco_ManageNodeID ) b on a.mano_ProjectID = b.otco_ProjectID and a.mano_ManageNodeID  = b.otco_ManageNodeID where a.mano_ProjectID = :projectId and mano_ManageNodeID=:parentId",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).putValue("parentId", parentId)
						.getMap());
		if (data == null) {
			return null;
		}
		List<Map<String, Object>> dataList = jdbcTemplateService.selectForList(
				"select mano_ManageNodeID ,mano_Code,mano_Name, GF1,SJ from td_ManageNode a left join (select otco_ProjectID,otco_ManageNodeID,max(case otco_CostType when '4' then otco_Formula end) as GF1,null as GF2, null as GF3,max(case otco_CostType when '5' then otco_Formula end) as SJ from td_OtherCost group by otco_ProjectID,otco_ManageNodeID ) b on a.mano_ProjectID = b.otco_ProjectID and a.mano_ManageNodeID  = b.otco_ManageNodeID where a.mano_ProjectID = :projectId and mano_ParentID=:parentId order by a.mano_IdxCode",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).putValue("parentId", parentId)
						.getMap());

		for (Map<String, Object> dataMap : dataList) {
			childList.add(MapUtil.create().putValue("id", dataMap.get("mano_ManageNodeID"))
					.putValue("nodeNumber", dataMap.get("mano_Code")).putValue("nodeName", dataMap.get("mano_Name"))
					.putValue("fees", dataMap.get("GF1") == null ? "" : dataMap.get("GF1") + "%")
					.putValue("taxesEqual", dataMap.get("SJ") == null ? "" : dataMap.get("SJ") + "%")
					.putValue("children", getGFSJChildrenNode(beSectionInfo.getTdProjectid(),
							StringUtil.toString(dataMap.get("mano_ManageNodeID"))))
					.getMap());
		}

		returnList.add(MapUtil.create().putValue("children", childList).putValue("id", data.get("mano_ManageNodeID"))
				.putValue("nodeNumber", StringUtil.toString(data.get("mano_Code")))
				.putValue("nodeName", StringUtil.toString(data.get("mano_Name")))
				.putValue("fees", data.get("GF1") == null ? "" : data.get("GF1") + "%")
				.putValue("taxesEqual", data.get("SJ") == null ? "" : data.get("SJ") + "%").getMap());
		return returnList;
	}

	/**
	 * 递归算法解析成树形结构
	 *
	 * @param defineId
	 * @param seqId
	 * @return
	 * @author daizhifeng
	 */
	public List<Map<String, Object>> getGFSJChildrenNode(String projectId, String seqId) {
		List<Map<String, Object>> returnList = Lists.newArrayList();
		// 遍历子节点
		for (Map<String, Object> dataMap : jdbcTemplateService.selectForList(
				"select mano_ManageNodeID ,mano_Code,mano_Name, GF1,SJ from td_ManageNode a left join (select otco_ProjectID,otco_ManageNodeID,max(case otco_CostType when '4' then otco_Formula end) as GF1,null as GF2, null as GF3,max(case otco_CostType when '5' then otco_Formula end) as SJ from td_OtherCost group by otco_ProjectID,otco_ManageNodeID ) b on a.mano_ProjectID = b.otco_ProjectID and a.mano_ManageNodeID  = b.otco_ManageNodeID where a.mano_ProjectID = :projectId and mano_ParentID=:parentId order by a.mano_IdxCode",
				MapUtil.create().putValue("projectId", projectId).putValue("parentId", seqId).getMap())) {
			if (!StringUtils.isEmpty(dataMap.get("mano_ManageNodeID"))) {
				returnList.add(MapUtil.create().putValue("id", dataMap.get("mano_ManageNodeID"))
						.putValue("nodeNumber", dataMap.get("mano_Code")).putValue("nodeName", dataMap.get("mano_Name"))
						.putValue("fees", dataMap.get("GF1") == null ? "" : dataMap.get("GF1") + "%")
						.putValue("taxesEqual", dataMap.get("SJ") == null ? "" : dataMap.get("SJ") + "%")
						.putValue("children",
								getGFSJChildrenNode(projectId, StringUtil.toString(dataMap.get("mano_ManageNodeID"))))
						.getMap());
			}

		}
		return returnList;
	}

	@Override
	public List<Map<String, Object>> selectCSFLTree(String sectionId, String parentId, String type) {
		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
		List<Map<String, Object>> returnList = Lists.newArrayList();
		List<Map<String, Object>> childList = Lists.newArrayList();
		Map<String, Object> data = jdbcTemplateService.selectForMap(
				"select * from td_ManageNode  a left join td_CostRate "
						+ "     b on a.mano_ProjectID = b.cora_ProjectID "
						+ "     and a.mano_ManageNodeID = b.cora_ManageNodeID "
						+ "     where a.mano_ProjectID = :projectId and mano_ManageNodeID=:parentId",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).putValue("parentId", parentId).getMap());
		if (data == null) {
			return null;
		}
		List<Map<String, Object>> dataList = jdbcTemplateService.selectForList(
				"select * from td_ManageNode  a left join td_CostRate "
						+ "     b on a.mano_ProjectID = b.cora_ProjectID "
						+ "     and a.mano_ManageNodeID = b.cora_ManageNodeID "
						+ "     where a.mano_ProjectID = :projectId and mano_ParentID=:parentId order by a.mano_IdxCode",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).putValue("parentId", parentId)
						.getMap());

		for (Map<String, Object> dataMap : dataList) {
			childList.add(MapUtil.create().putValue("id", dataMap.get("mano_ManageNodeID"))
					.putValue("nodeNumber", dataMap.get("mano_Code")).putValue("nodeName", dataMap.get("mano_Name"))
					.putValue("enterpriseManagement", dataMap.get("cora_GLFUnder"))
					.putValue("CostConstruction", dataMap.get("cora_HJBHUnder"))
					.putValue("increaseInWinter", dataMap.get("cora_DJSGUnder"))
					.putValue("SecondaryHandlingFee", dataMap.get("cora_ECBYUnder"))
					.putValue("drivingPedestrian", dataMap.get("cora_XCGRUnder"))
					.putValue("completionInAdvance", dataMap.get("cora_TQJGUnder"))
					.putValue("children", getCSFLChildrenNode(beSectionInfo.getTdProjectid(),
							StringUtil.toString(dataMap.get("mano_ManageNodeID")),type))
					.getMap());
		}

		returnList.add(MapUtil.create().putValue("children", childList).putValue("id", data.get("mano_ManageNodeID"))
				.putValue("nodeNumber", data.get("mano_Code")).putValue("nodeName", data.get("mano_Name"))
				.putValue("nodeName", data.get("mano_Name")).putValue("enterpriseManagement", data.get("cora_GLFUnder"))
				.putValue("CostConstruction", data.get("cora_HJBHUnder"))
				.putValue("increaseInWinter", data.get("cora_DJSGUnder"))
				.putValue("SecondaryHandlingFee", data.get("cora_ECBYUnder"))
				.putValue("drivingPedestrian", data.get("cora_XCGRUnder"))
				.putValue("completionInAdvance", data.get("cora_TQJGUnder")).getMap());
		logger.info(returnList);
		return returnList;
	}

	@Override
	public List<BeSectionParameter> queryListByParamIds(String sectionId, String[] array) throws Exception {
		return beSectionParameterMapper.queryListByParamIds(sectionId, array);
	}

	@Override
	public boolean saveSectionParameter(List<BeSectionParameter> beSectionParameterList) throws Exception {
		BeSectionParameterKey beSectionParameterKey = new BeSectionParameterKey();
		for (BeSectionParameter beSectionParameter : beSectionParameterList) {
			beSectionParameterKey.setSectionId(beSectionParameter.getSectionId());
			beSectionParameterKey.setParamId(beSectionParameter.getParamId());
			if (beSectionParameterMapper.selectByPrimaryKey(beSectionParameterKey) == null) {
				// 保存操作
				if (beSectionParameterMapper.insert(beSectionParameter) < 1) {
					return false;
				}
			} else {
				// 更新操作
				if (beSectionParameterMapper.updateByPrimaryKeySelective(beSectionParameter) < 1) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 递归算法解析成树形结构
	 *
	 * @param defineId
	 * @param seqId
	 * @return
	 * @author daizhifeng
	 */
	public List<Map<String, Object>> getCSFLChildrenNode(String projectId, String seqId,String type) {

		List<Map<String, Object>> returnList = Lists.newArrayList();

		// 遍历子节点
		for (Map<String, Object> dataMap : jdbcTemplateService.selectForList(
				"select * from td_ManageNode  a left join td_CostRate "
						+ "    b on a.mano_ProjectID = b.cora_ProjectID "
						+ "    and a.mano_ManageNodeID = b.cora_ManageNodeID "
						+ "	 where a.mano_ProjectID = :projectId and mano_ParentID=:parentId order by a.mano_IdxCode",
				MapUtil.create().putValue("projectId", projectId).putValue("parentId", seqId).getMap())) {
			if (!StringUtils.isEmpty(dataMap.get("mano_ManageNodeID"))) {
				returnList.add(MapUtil.create().putValue("id", dataMap.get("mano_ManageNodeID"))
						.putValue("nodeNumber", dataMap.get("mano_Code")).putValue("nodeName", dataMap.get("mano_Name"))
						.putValue("enterpriseManagement", dataMap.get("cora_GLFUnder"))
						.putValue("CostConstruction", dataMap.get("cora_HJBHUnder"))
						.putValue("increaseInWinter", dataMap.get("cora_DJSGUnder"))
						.putValue("SecondaryHandlingFee", dataMap.get("cora_ECBYUnder"))
						.putValue("drivingPedestrian", dataMap.get("cora_XCGRUnder"))
						.putValue("completionInAdvance", dataMap.get("cora_TQJGUnder"))
						.putValue("children",
								getCSFLChildrenNode(projectId, StringUtil.toString(dataMap.get("mano_ManageNodeID")),type))
						.getMap());
			}

		}
		return returnList;
	}

	@Override
	public int selectCountBySectionId(String sectionId, String paramType) {
		return beSectionParameterMapper.selectCountBySectionId(sectionId, paramType);
	}

	@Override
	public List<Map<String, Object>> queryTdAuditparaBytype(String tdProjectId, Integer paraType) throws Exception {
		return beSectionParameterMapper.queryTdAuditparaBytype(tdProjectId, paraType);
	}
}
